﻿using System;
using System.Text.RegularExpressions;
using System.Web;
using OLAP.Common;
using OLAP.Models;
using OLAP.Models.Partials;

namespace OLAP
{
    /// <summary>
    /// Summary description for Attachments
    /// </summary>
    public class Attachments : IHttpHandler
    {
        private static int cacheDuration;

        static Attachments()
        {
            cacheDuration = Utility.GetCacheProfileSetting("AttachmentData", 60);
        }

        public void ProcessRequest(HttpContext context)
        {
            Int64 id;
            byte[] buffer;
            string uri, cacheKey;
            object obj;
            Attachment Attachment;

            if (context.Request.QueryString["id"] == null || !Int64.TryParse(context.Request.QueryString["id"], out id))
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("No ID set!");
                return;
            }

            cacheKey = String.Concat("AttachmentData_", id);
            obj = HttpRuntime.Cache[cacheKey];
            if (obj == null)
            {
                PressreleasesRepository pr = new PressreleasesRepository();
                Attachment = pr.GetAttactmentById(id);
                GC.Collect();
                HttpRuntime.Cache.Insert(cacheKey, Attachment, null, DateTime.UtcNow.AddSeconds(cacheDuration), System.Web.Caching.Cache.NoSlidingExpiration);
            }
            else
            {
                Attachment = (Attachment)obj;
            }

            context.Response.Clear();
            context.Response.ClearHeaders();

            /*
            //Because this would essentially cahce the file, then our current corporate policy is not to cache large files like this at all! 
            context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate); 
            context.Response.Cache.VaryByParams["id"] = true;
            */

            //Cache settings for the client side.
            TimeSpan expire = new TimeSpan(0, 0, cacheDuration);
            context.Response.Cache.SetCacheability(HttpCacheability.Private);
            context.Response.Cache.SetExpires(DateTime.Now.Add(expire));
            context.Response.Cache.SetMaxAge(expire);

            context.Response.Cache.SetValidUntilExpires(true);
            //context.Response.AddHeader("Last-Modified", currentDocument.LastUpdated.ToLongDateString());


            context.Response.AppendHeader("Content-Type", "application/force-download");
            context.Response.AddHeader("content-disposition", "attachment; filename=" + Attachment.FileName);
            context.Response.AppendHeader("Content-Type", Attachment.MimeType);

            if (Attachment.MimeType.ToLower() == "application/octet-stream")
            {
                Match match = Regex.Match(Attachment.FileName, @"\..*?$", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                if (match.Success)
                {
                    switch (match.Value.ToLower())
                    {
                        case ".xlsx":
                            context.Response.AppendHeader("Content-Type", "application/vnd.ms-excel");
                            break;
                    }
                }
            }
            context.Response.BinaryWrite(Attachment.MediaBinary);
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}